import {
	Collapse,
	Form,
	Row,
	Col,
	Input,
	Select,
	DatePicker,
	Cascader,
	InputNumber,
	Button,
} from 'antd'
import moment from 'moment'
import React, {forwardRef, useImperativeHandle, useEffect} from 'react'
import {PlusCircleOutlined, MinusCircleOutlined} from '@ant-design/icons'
import styles from './index.less'

const {Panel} = Collapse
const {Option} = Select
const {TextArea} = Input
type PropsType = {
	type: string | undefined
	dictData: any
	citysList: any
	dataSource: any
}

const managementSupplier = (props: PropsType, ref: any) => {
	const {type, dictData, citysList, dataSource} = props
	const [basicsForm] = Form.useForm()
	const [bankForm] = Form.useForm()
	useEffect(() => {
		if (type !== 'add') {
			const data = dataSource.handle
			basicsForm.setFieldsValue({
				...data,
				city: data?.cityId ? [data?.provinceId, data?.cityId] : [],
				establishDate: moment(data?.establishDate),
				automobileBusinessTime: moment(data?.establishDate),
				headquarters: data?.headquarters?.split(',')?.map(Number),
				isIllegal: data?.isIllegal === 0 ? undefined : data?.isIllegal,
				isFinancialEmbroilment:
					data?.isFinancialEmbroilment === 0
						? undefined
						: data?.isFinancialEmbroilment,
			})
			const newBankData = dataSource?.bankData
			dataSource?.bankData?.forEach((items: any, index: number) => {
				delete newBankData[index]?.id
				newBankData[index].bankProvince = items?.bankProvince
					?.split(',')
					?.map(Number)
			})
			bankForm.setFieldsValue({bankData: newBankData})
		} else {
			basicsForm.setFieldsValue({
				...dataSource,
				city: dataSource?.cityId
					? [dataSource?.provinceId, dataSource?.cityId]
					: '',
				establishDate: dataSource?.establishDate
					? moment(dataSource?.establishDate)
					: '',
				automobileBusinessTime: dataSource?.establishDate
					? moment(dataSource?.establishDate)
					: '',
				headquarters:
					dataSource?.headquarters?.split(',')?.map(Number) || '',
			})
			// 初始一条银行信息
			bankForm.setFieldsValue({
				bankData: [
					{
						bankAccount: undefined,
						accountBankName: undefined,
						bankName: undefined,
						bankProvince: undefined,
					},
				],
			})
		}
	}, [type, dataSource])

	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)
	const onSubmit = async () => {
		const basicsValue = await basicsForm.validateFields()
		const bankValue = await bankForm.validateFields()
		if (basicsValue && bankValue) {
			const newBankData = bankValue?.bankData?.map(
				(items: {[x: string]: any; bankProvince: any}) => {
					const {bankProvince, ...info} = items
					return {...info, bankProvince: bankProvince?.toString()}
				},
			)
			return {
				...basicsValue,
				bankData: newBankData,
				provinceId: basicsValue?.city?.[0],
				cityId: basicsValue?.city?.[1],
				establishDate: moment(basicsValue?.establishDate).format(
					'YYYY-MM-DD',
				),
				automobileBusinessTime: moment(
					basicsValue?.automobileBusinessTime,
				).format('YYYY-MM-DD'),
				headquarters: basicsValue?.headquarters?.toString(),
			}
		}
		return {}
	}
	useImperativeHandle(ref, () => ({
		getData: onSubmit,
	}))

	return (
		<div className={styles.channelSupplier}>
			<Collapse
				defaultActiveKey={['1', '2']}
				ghost
				expandIconPosition="end"
				collapsible="header">
				<Panel header={customizeHeader('基础信息')} key="1" forceRender>
					<Form
						form={basicsForm}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '151px'}}
						labelAlign="right"
						labelWrap
						autoComplete="off"
						disabled={type === 'view' || type === 'process'}>
						<Row gutter={12}>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="企业性质"
									name="enterpriseNature"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Enterprise_Nature}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="注册城市"
									name="city"
									rules={[{required: true}]}>
									<Cascader
										fieldNames={{
											label: 'name',
											value: 'id',
											children: 'cityInfoList',
										}}
										options={citysList}
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="成立日期"
									name="establishDate"
									rules={[{required: true}]}>
									<DatePicker
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="从事汽车，二手车业务时间"
									name="automobileBusinessTime"
									rules={[{required: true}]}>
									<DatePicker
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="近一年月均二手车交易量"
									name="carTransactionVolume"
									rules={[{required: true}]}>
									<InputNumber
										formatter={(value) => {
											if (
												type === 'view' ||
												type === 'process'
											) {
												return `${value}台/月`
											}
											return value?.toString() || ''
										}}
										addonAfter="台/月"
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="总部/区域"
									name="headquarters"
									rules={[{required: true}]}>
									<Cascader
										fieldNames={{
											label: 'name',
											value: 'id',
											children: 'cityInfoList',
										}}
										options={citysList}
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="品类"
									name="category"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Category}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="开票税率"
									name="invoicingRate"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear
										fieldNames={{
											value: 'dictKey',
											label: 'dictValue',
										}}
										options={dictData?.Invoicing_Tax_Rate}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="联系人"
									name="contacts"
									rules={[{required: true, max: 6}]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="联系人手机"
									name="mobilePhone"
									rules={[
										{required: true},
										{
											pattern:
												/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
											message: '请输入正确的手机号',
										},
									]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="联系人邮箱"
									name="email"
									rules={[
										{required: true},
										{
											type: 'email',
											message: '填写的邮箱格式有误',
										},
									]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="常用地址"
									name="address"
									rules={[{required: true, max: 30}]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="邮编"
									name="postalCode"
									rules={[
										{
											pattern: /^[0-9]\d{5}$/,
											message: '请输入正确的邮编',
										},
									]}>
									<Input
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入'
										}
									/>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="公司和法人是否有违法违规记录"
									name="isIllegal"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear>
										<Option value={1}>是</Option>
										<Option value={2}>否</Option>
									</Select>
								</Form.Item>
							</Col>
							<Col sm={{span: 24}} md={{span: 12}} lg={{span: 8}}>
								<Form.Item
									label="公司目前是否有债务财务纠纷"
									name="isFinancialEmbroilment"
									rules={[{required: true}]}>
									<Select
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请选择'
										}
										allowClear>
										<Option value={1}>是</Option>
										<Option value={2}>否</Option>
									</Select>
								</Form.Item>
							</Col>
							<Col span={16}>
								<Form.Item
									label="公司服务的主要企业或参与的重要项目"
									name="enterpriseProject"
									rules={[{required: true}]}>
									<TextArea
										maxLength={200}
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入（最多200个字）'
										}
										autoSize={{minRows: 3, maxRows: 6}}
									/>
								</Form.Item>
							</Col>
							<Col span={16}>
								<Form.Item
									label="公司侧重/倾向于哪些车型的处置业务？"
									name="handleBusiness"
									rules={[{required: true}]}>
									<TextArea
										maxLength={200}
										placeholder={
											type === 'view' ||
											type === 'process'
												? '-'
												: '请输入（最多200个字）'
										}
										autoSize={{minRows: 3, maxRows: 6}}
									/>
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Panel>
				<Panel header={customizeHeader('银行信息')} key="2" forceRender>
					<Form
						form={bankForm}
						name="basic"
						layout="horizontal"
						labelCol={{flex: '140px'}}
						labelAlign="right"
						labelWrap
						disabled={type === 'view' || type === 'process'}
						autoComplete="off">
						<Form.List name="bankData">
							{(fields, {add, remove}) => (
								<>
									{fields.map((field, index) => (
										<Row gutter={12} key={field.key}>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="银行名称"
													name={[
														field.name,
														'bankName',
													]}
													rules={[
														{
															required: true,
															max: 20,
														},
														{
															pattern:
																/^[\u4e00-\u9fa5]{0,}$/,
															message:
																'银行名称只能输入文字',
														},
													]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="银行支行名称"
													name={[
														field.name,
														'accountBankName',
													]}
													rules={[
														{
															required: true,
															max: 20,
														},
														{
															pattern:
																/^[\u4e00-\u9fa5]{0,}$/,
															message:
																'银行支行名称只能输入文字',
														},
													]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="开户账号"
													name={[
														field.name,
														'bankAccount',
													]}
													rules={[{required: true}]}>
													<Input
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请输入'
														}
													/>
												</Form.Item>
											</Col>
											<Col
												sm={{span: 24}}
												md={{span: 12}}
												lg={{span: 8}}>
												<Form.Item
													label="银行省份/城市"
													name={[
														field.name,
														'bankProvince',
													]}
													rules={[{required: true}]}>
													<Cascader
														fieldNames={{
															label: 'name',
															value: 'id',
															children:
																'cityInfoList',
														}}
														options={citysList}
														placeholder={
															type === 'view' ||
															type === 'process'
																? '-'
																: '请选择'
														}
													/>
												</Form.Item>
											</Col>
											{index === 0 ||
											type === 'view' ||
											type === 'process' ? (
												''
											) : (
												<Col
													sm={{span: 24}}
													md={{span: 12}}
													lg={{span: 8}}>
													<MinusCircleOutlined
														className={
															styles.remove
														}
														onClick={() =>
															remove(index)
														}
													/>
												</Col>
											)}
										</Row>
									))}
									{fields?.length < 5 &&
									type !== 'view' &&
									type !== 'process' ? (
										<Form.Item>
											<Button
												type="link"
												icon={<PlusCircleOutlined />}
												onClick={() => add()}>
												添加账号信息
											</Button>
										</Form.Item>
									) : (
										''
									)}
								</>
							)}
						</Form.List>
					</Form>
				</Panel>
			</Collapse>
		</div>
	)
}

export default forwardRef(managementSupplier)
